import api from '@/utils/api'

// 监控相关API
export const monitoringApi = {
  // 获取监控摘要
  getSummary() {
    return api.get('/monitoring/metrics/summary/')
  },

  // 获取实时监控数据
  getRealtimeMetrics() {
    return api.get('/monitoring/metrics/realtime/')
  },

  // 获取监控统计数据
  getMetricsStats(params: {
    host_id: number
    time_range: string
    metrics: string[]
  }) {
    return api.post('/monitoring/metrics/stats/', params)
  },

  // 获取主机监控历史
  getHostMetrics(hostId: number, params?: any) {
    return api.get(`/monitoring/metrics/`, {
      params: { host: hostId, ...params }
    })
  },

  // 获取进程信息
  getProcessInfo(hostId: number) {
    return api.get('/monitoring/process/', {
      params: { host: hostId }
    })
  },

  // 获取服务状态
  getServiceStatus(hostId: number) {
    return api.get('/monitoring/services/', {
      params: { host: hostId }
    })
  },

  // 获取告警规则
  getAlertRules() {
    return api.get('/monitoring/alerts/')
  },

  // 创建告警规则
  createAlertRule(data: any) {
    return api.post('/monitoring/alerts/', data)
  },

  // 更新告警规则
  updateAlertRule(id: number, data: any) {
    return api.put(`/monitoring/alerts/${id}/`, data)
  },

  // 删除告警规则
  deleteAlertRule(id: number) {
    return api.delete(`/monitoring/alerts/${id}/`)
  }
}

// CMDB相关API
export const cmdbApi = {
  // 获取主机列表
  getHosts(params?: any) {
    return api.get('/cmdb/hosts/', { params })
  },

  // 获取主机详情
  getHost(id: number) {
    return api.get(`/cmdb/hosts/${id}/`)
  },

  // 创建主机
  createHost(data: any) {
    return api.post('/cmdb/hosts/', data)
  },

  // 更新主机
  updateHost(id: number, data: any) {
    return api.put(`/cmdb/hosts/${id}/`, data)
  },

  // 删除主机
  deleteHost(id: number) {
    return api.delete(`/cmdb/hosts/${id}/`)
  },

  // 测试主机连接
  testConnection(id: number, data?: any) {
    return api.post(`/cmdb/hosts/${id}/test_connection/`, data)
  },

  // 切换监控状态
  toggleMonitoring(id: number, enabled: boolean) {
    return api.post(`/cmdb/hosts/${id}/toggle_monitoring/`, { enabled })
  },

  // 更新主机状态
  updateHostStatus(id: number, status: string) {
    return api.post(`/cmdb/hosts/${id}/update_status/`, { status })
  },

  // 批量操作主机
  batchOperation(data: {
    host_ids: number[]
    operation: string
    parameters?: any
  }) {
    return api.post('/cmdb/hosts/batch_operation/', data)
  },

  // 获取主机摘要
  getHostSummary() {
    return api.get('/cmdb/hosts/summary/')
  },

  // 获取环境列表
  getEnvironments() {
    return api.get('/cmdb/environments/')
  },

  // 获取激活的环境
  getActiveEnvironments() {
    return api.get('/cmdb/environments/active/')
  },

  // 获取主机类型列表
  getHostTypes() {
    return api.get('/cmdb/host-types/')
  },

  // 获取激活的主机类型
  getActiveHostTypes() {
    return api.get('/cmdb/host-types/active/')
  },

  // 获取主机组列表
  getHostGroups() {
    return api.get('/cmdb/host-groups/')
  },

  // 获取激活的主机组
  getActiveHostGroups() {
    return api.get('/cmdb/host-groups/active/')
  }
}

// SSH相关API
export const sshApi = {
  // 获取SSH会话列表
  getSessions(params?: any) {
    return api.get('/ssh/sessions/', { params })
  },

  // 获取会话命令历史
  getSessionCommands(sessionId: string, params?: any) {
    return api.get(`/ssh/sessions/${sessionId}/commands/`, { params })
  },

  // 获取连接池状态
  getConnectionPool() {
    return api.get('/ssh/connections/')
  },

  // 清理连接池
  cleanupConnections() {
    return api.post('/ssh/connections/cleanup/')
  },

  // 获取SSH配置
  getSSHConfig() {
    return api.get('/ssh/config/')
  },

  // 更新SSH配置
  updateSSHConfig(data: any) {
    return api.put('/ssh/config/', data)
  }
}

// WebSocket连接管理
export class SSHWebSocket {
  private ws: WebSocket | null = null
  private hostId: number
  private callbacks: {
    onOpen?: () => void
    onMessage?: (data: any) => void
    onClose?: () => void
    onError?: (error: Event) => void
  } = {}

  constructor(hostId: number) {
    this.hostId = hostId
  }

  connect(callbacks: {
    onOpen?: () => void
    onMessage?: (data: any) => void
    onClose?: () => void
    onError?: (error: Event) => void
  }) {
    this.callbacks = callbacks
    
    // 构建WebSocket URL
    const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'
    const host = window.location.host
    const wsUrl = `${protocol}//${host}/ws/ssh/${this.hostId}/`
    
    this.ws = new WebSocket(wsUrl)
    
    this.ws.onopen = () => {
      console.log('SSH WebSocket连接已建立')
      this.callbacks.onOpen?.()
    }
    
    this.ws.onmessage = (event) => {
      try {
        const data = JSON.parse(event.data)
        this.callbacks.onMessage?.(data)
      } catch (error) {
        console.error('解析WebSocket消息失败:', error)
      }
    }
    
    this.ws.onclose = () => {
      console.log('SSH WebSocket连接已关闭')
      this.callbacks.onClose?.()
    }
    
    this.ws.onerror = (error) => {
      console.error('SSH WebSocket错误:', error)
      this.callbacks.onError?.(error)
    }
  }

  send(data: any) {
    if (this.ws && this.ws.readyState === WebSocket.OPEN) {
      this.ws.send(JSON.stringify(data))
    } else {
      console.warn('WebSocket未连接，无法发送消息')
    }
  }

  close() {
    if (this.ws) {
      this.ws.close()
      this.ws = null
    }
  }

  get readyState() {
    return this.ws?.readyState || WebSocket.CLOSED
  }
}

// 导出默认API实例
export default {
  monitoring: monitoringApi,
  cmdb: cmdbApi,
  ssh: sshApi,
  SSHWebSocket
}
